package org.abhigarde.personalexpense.dao;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.List;

import org.abhigarde.personalexpense.model.Expense;
import org.abhigarde.utils.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class ExpenseDAO {
	public long saveExpense(String category,String product,BigDecimal cost,Date purchaseDate)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Long id = null;
		try {
			transaction = session.beginTransaction();
			Expense expense = new Expense();
			expense.setCategory(category);
			expense.setProduct(product);
			expense.setCost(cost);
			expense.setPurachseDate(purchaseDate);
			expense.setCreatedBy("My Application");
			expense.setCreationDate(new Date(System.currentTimeMillis()));
			id = (Long) session.save(expense);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return id;
	}

	@SuppressWarnings("unchecked")
	public void listExpenses()
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			List<Expense> expenses = session.createQuery("from Expense").list();

			for (Expense expense : expenses){
				System.out.println(expense.getCategory());
				System.out.println(expense.getProduct());
				System.out.println(expense.getCost());
			}

			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public void updateExpense(Long id, String category,String product,BigDecimal cost)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Expense expense = (Expense) session.get(Expense.class, id);
			expense.setCategory(category);
			expense.setProduct(product);
			expense.setCost(cost);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public void deleteExpense(Long id)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Expense expense = (Expense) session.get(Expense.class, id);
			session.delete(expense);
			transaction.commit();
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
